//
//  QHDeviceInfoTools.m
//  Common
//
//  Created by 启航龙图.在线事业部.李东 on 2021/1/4.
//

#import "QHDeviceInfoTools.h"
#import "sys/utsname.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <sys/sysctl.h>
#import <UIKit/UIKit.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "IQHReachabilityManager.h"

static const char *SIDFAMachine = "hw.machine";
static NSString *getSystemHardwareByName(const char *typeSpecifier) {
    size_t size;
    sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
    char *answer = malloc(size);
    sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
    NSString *results = [NSString stringWithUTF8String:answer];
    free(answer);
    return results;
}

@implementation QHDeviceInfoTools

+ (NSString *)getDeviceInfo
{
    return [NSString stringWithFormat:@"设备信息:%@——iOS版本:%@——IP地址:%@",[self deviceModel],[self system_version],[self getIPAddress]];
}

+ (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

+ (NSString *)deviceBrands
{
    return @"Apple";
}

+ (NSString *)freeSize
{
    /// 总大小
    float totalsize = 0.0;
    /// 剩余大小
    float freesize = 0.0;
    /// 是否登录
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    if (dictionary)
    {
        NSNumber *_free = [dictionary objectForKey:NSFileSystemFreeSize];
        freesize = [_free unsignedLongLongValue]*1.0/(1024);
        
        NSNumber *_total = [dictionary objectForKey:NSFileSystemSize];
        totalsize = [_total unsignedLongLongValue]*1.0/(1024);
        
        //        IQHLog(@" totalsize %f G,freesize %f G",totalsize/1024.0/1024.0,freesize/1024.0/1024.0);
    } else
    {
        //        IQHLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
    }
    
    return [NSString stringWithFormat:@"%0.2f",freesize/1024.0/1024.0];
}


+ (NSString *)getWebviewAppInfo
{
    NSString *currentVersion = [self app_version];
    return [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];;
}

/// UserAgentInfo
+ (NSString *)getUserAgentInfo
{
    return [NSString stringWithFormat:@"iPhone/%@; iOS/%@; iqihang/%@",[self deviceModel],[self system_version],[self app_version]];;
}

/// app名称
+ (NSString *)app_name
{
    return [[self infoDictionary] objectForKey:@"CFBundleDisplayName"];
}

/// app版本
+ (NSString *)app_version
{
    return [[self infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

/// app build版本
+ (NSString *)app_build
{
    return [[self infoDictionary] objectForKey:@"CFBundleVersion"];
}

///// 手机序列号
//+ (NSString *)phone_identifierNumber
//{
//    return [[UIDevice currentDevice] uniqueIdentifier];
//}

/// 手机别名： 用户定义的名称
+ (NSString *)phone_userPhoneName
{
    return [[UIDevice currentDevice] name];
}

/// 设备名称
+ (NSString *)device_name
{
    return [[UIDevice currentDevice] systemName];
}

/// 设备系统版本号
+ (NSString *)system_version
{
    return [NSString stringWithFormat:@"%f", [[UIDevice currentDevice].systemVersion doubleValue]];;
}

/// 手机型号
+ (NSString *)device_model
{
    return [[UIDevice currentDevice] model];
}

/// 地方型号  （国际化区域名称）
+ (NSString *)localPhoneModel
{
    return [[UIDevice currentDevice] localizedModel];
}

/// machine
+ (NSString *)machine
{
    NSString *machine = getSystemHardwareByName(SIDFAMachine);
    return machine == nil ? @"" : machine;
}

/// 运营商
+ (NSString* )carrierInfo {
     #if TARGET_IPHONE_SIMULATOR
         return @"SIMULATOR";
     #else
     static dispatch_queue_t _queue;
     static dispatch_once_t once;
     dispatch_once(&once, ^{
         _queue = dispatch_queue_create([[NSString stringWithFormat:@"com.carr.%@"
         , self] UTF8String], NULL);
     });
     __block NSString *  carr = nil;
     dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
     dispatch_async(_queue, ^(){
         CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
         CTCarrier *carrier = nil;
         if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 12.1) {
             if ([info respondsToSelector:@selector(serviceSubscriberCellularProviders)]) {
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wunguarded-availability-new"
                 NSArray *carrierKeysArray = [info.serviceSubscriberCellularProviders.allKeys sortedArrayUsingSelector:@selector(compare:)];
                 carrier = info.serviceSubscriberCellularProviders
                 [carrierKeysArray.firstObject];
                 if (!carrier.mobileNetworkCode) {
                     carrier = info.serviceSubscriberCellularProviders
                     [carrierKeysArray.lastObject];
                }
#pragma clang diagnostic pop
            }
         }
        if(!carrier) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored  "-Wdeprecated-declarations"
            carrier = info.subscriberCellularProvider;
#pragma clang diagnostic pop
        } else {
            if (carrier != nil) {
                NSString *networkCode = [carrier mobileNetworkCode];
                NSString *countryCode = [carrier mobileCountryCode];
                if (countryCode && [countryCode isEqualToString:@"460"] && networkCode)
                    if ([networkCode isEqualToString:@"00"] ||
                        [networkCode isEqualToString:@"02"] ||
                        [networkCode isEqualToString:@"07"] ||
                        [networkCode isEqualToString:@"08"]) { carr= @"中国移动"; }
                    if ([networkCode isEqualToString:@"01"]
                        || [networkCode isEqualToString:@"06"]
                        || [networkCode isEqualToString:@"09"]) { carr= @"中国联通"; }
                    if ([networkCode isEqualToString:@"03"]
                        || [networkCode isEqualToString:@"05"]
                        || [networkCode isEqualToString:@"11"]) { carr= @"中国电信"; }
                    if ([networkCode isEqualToString:@"04"]) { carr= @"中国卫通"; }
                    if ([networkCode isEqualToString:@"20"]) { carr= @"中国铁通"; }
                }else {
                    carr = [carrier.carrierName copy];
                }
            }
         if (carr.length <= 0) { carr =  @"unknown"; }
        dispatch_semaphore_signal(semaphore);
     });
    dispatch_time_t  t = dispatch_time(DISPATCH_TIME_NOW, 0.5* NSEC_PER_SEC);
 
    dispatch_semaphore_wait(semaphore, t);
        return [carr copy];
    #endif
}
 

/// 获取App的信息
+ (NSDictionary *)infoDictionary
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return infoDictionary;
}

/// 当前网络连接
+ (NSString *)networkStatus
{
    IQHReachabilityStatus networkStatus = [IQHReachabilityManager sharedManager].networkReachabilityStatus;
    switch (networkStatus) {
        case IQHReachabilityStatusUnknown:
            return @"未知网络";
            break;
        case IQHReachabilityStatusNotReachable:
            return @"无网络连接";
            break;
        case IQHReachabilityStatusReachableViaWWAN:
            return [self getNetType];
            break;
        case IQHReachabilityStatusReachableViaWiFi:
            return @"WiFi";
            break;
            
        default:
            break;
    }
}

+ (NSString *)getNetType
{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    NSString *currentStatus = info.currentRadioAccessTechnology;
    NSString *currentNet = @"5G";
    
    if ([currentStatus isEqualToString:CTRadioAccessTechnologyGPRS]) {
        currentNet = @"GPRS";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyEdge]) {
        currentNet = @"2.75G EDGE";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyWCDMA]){
        currentNet = @"3G";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyHSDPA]){
        currentNet = @"3.5G HSDPA";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyHSUPA]){
        currentNet = @"3.5G HSUPA";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMA1x]){
        currentNet = @"2G";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]){
        currentNet = @"3G";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]){
        currentNet = @"3G";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]){
        currentNet = @"3G";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyeHRPD]){
        currentNet = @"HRPD";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyLTE]){
        currentNet = @"4G";
    }else if (@available(iOS 14.0, *)) {
        if ([currentStatus isEqualToString:CTRadioAccessTechnologyNRNSA]){
            currentNet = @"5G NSA";
        }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyNR]){
            currentNet = @"5G";
        }
    }
    return currentNet;
}

/// 设备类型
+ (NSString *)deviceType
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return @"iPhone";
    } else {
        return @"iPad";
    }
}

/// 设备型号
+ (NSString *)deviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4s (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"CN_JP_HKiPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"HK_CNiPhone 7 Plus";
    if ([platform isEqualToString:@"iPhone9,3"]) return @"EN_TWiPhone 7";
    if ([platform isEqualToString:@"iPhone9,4"]) return @"EN_TWiPhone 7 Plus";
    if ([platform isEqualToString:@"iPhone10,1"]) return @"CN(A1863)_JP(A1906)iPhone 8";
    if ([platform isEqualToString:@"iPhone10,4"]) return @"EN(Global/A1905)iPhone 8";
    if ([platform isEqualToString:@"iPhone10,2"]) return @"CN(A1864)_JP(A1898)iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,5"]) return @"EN(Global/A1897)iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,3"]) return @"CN(A1865)_日行(A1902)iPhone X";
    if ([platform isEqualToString:@"iPhone10,6"]) return @"EN(Global/A1901)iPhone X";
    if ([platform isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if ([platform isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    if ([platform isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    if ([platform isEqualToString:@"iPhone12,1"]) return @"iPhone 11";
    if ([platform isEqualToString:@"iPhone12,3"]) return @"iPhone 11 Pro";
    if ([platform isEqualToString:@"iPhone12,5"]) return @"iPhone 11 Pro Max";
    if ([platform isEqualToString:@"iPhone12,8"]) return @"iPhone SE (2nd generation)";
    if ([platform isEqualToString:@"iPhone13,1"]) return @"iPhone 12 mini";
    if ([platform isEqualToString:@"iPhone13,2"]) return @"iPhone 12";
    if ([platform isEqualToString:@"iPhone13,3"]) return @"iPhone 12 Pro";
    if ([platform isEqualToString:@"iPhone13,4"]) return @"iPhone 12 Pro Max";
    
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    if ([platform isEqualToString:@"iPad4,7"])      return @"iPad Mini 3";
    if ([platform isEqualToString:@"iPad4,8"])      return @"iPad Mini 3";
    if ([platform isEqualToString:@"iPad4,9"])      return @"iPad Mini 3";
    if ([platform isEqualToString:@"iPad5,1"])      return @"iPad Mini 4 (WiFi)";
    if ([platform isEqualToString:@"iPad5,2"])      return @"iPad Mini 4 (LTE)";
    if ([platform isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad6,3"])      return @"iPad Pro 9.7";
    if ([platform isEqualToString:@"iPad6,4"])      return @"iPad Pro 9.7";
    if ([platform isEqualToString:@"iPad6,7"])      return @"iPad Pro 12.9";
    if ([platform isEqualToString:@"iPad6,8"])      return @"iPad Pro 12.9";
    if ([platform isEqualToString:@"iPad6,11"])    return @"iPad 5 (WiFi)";
    if ([platform isEqualToString:@"iPad6,12"])    return @"iPad 5 (Cellular)";
    if ([platform isEqualToString:@"iPad7,1"])     return @"iPad Pro 12.9 inch 2nd gen (WiFi)";
    if ([platform isEqualToString:@"iPad7,2"])     return @"iPad Pro 12.9 inch 2nd gen (Cellular)";
    if ([platform isEqualToString:@"iPad7,3"])     return @"iPad Pro 10.5 inch (WiFi)";
    if ([platform isEqualToString:@"iPad7,4"])     return @"iPad Pro 10.5 inch (Cellular)";
    if ([platform isEqualToString:@"iPad7,5"])     return @"iPad (6th generation)(J71bAP)";
    if ([platform isEqualToString:@"iPad7,6"])     return @"iPad (6th generation)(J72bAP)";
    if ([platform isEqualToString:@"iPad7,11"])     return @"iPad (7th generation)(J171AP)";
    if ([platform isEqualToString:@"iPad7,12"])     return @"iPad (7th generation)(J172AP)";
    
    if ([platform isEqualToString:@"iPad11,1"])     return @"iPad mini (5th generation)";
    if ([platform isEqualToString:@"iPad11,2"])     return @"iPad mini (5th generation)";
    if ([platform isEqualToString:@"iPad11,3"])     return @"iPad Air (3rd generation)(J217AP)";
    if ([platform isEqualToString:@"iPad11,4"])     return @"iPad Air (3rd generation)(J218AP)";
    if ([platform isEqualToString:@"iPad11,6"])     return @"iPad (8th generation)(J171aAP)";
    if ([platform isEqualToString:@"iPad11,7"])     return @"iPad (8th generation)(J172aAP)";
    if ([platform isEqualToString:@"iPad13,1"])     return @"iPad Air (4th generation)(J307AP)";
    if ([platform isEqualToString:@"iPad13,2"])     return @"iPad Air (4th generation)(J308AP)";
    
    if ([platform isEqualToString:@"iPad8,1"])     return @"iPad Pro (11-inch)";
    if ([platform isEqualToString:@"iPad8,2"])     return @"iPad Pro (11-inch)";
    if ([platform isEqualToString:@"iPad8,3"])     return @"iPad Pro (11-inch)";
    if ([platform isEqualToString:@"iPad8,4"])     return @"iPad Pro (11-inch)";
    if ([platform isEqualToString:@"iPad8,5"])     return @"iPad Pro (12.9-inch) (3rd generation)";
    if ([platform isEqualToString:@"iPad8,6"])     return @"iPad Pro (12.9-inch) (3rd generation)";
    if ([platform isEqualToString:@"iPad8,7"])     return @"iPad Pro (12.9-inch) (3rd generation)";
    if ([platform isEqualToString:@"iPad8,8"])     return @"iPad Pro (12.9-inch) (3rd generation)";
    if ([platform isEqualToString:@"iPad8,9"])     return @"iPad Pro (11-inch) (2nd generation)";
    if ([platform isEqualToString:@"iPad8,10"])     return @"iPad Pro (11-inch) (2nd generation)";
    if ([platform isEqualToString:@"iPad8,11"])     return @"iPad Pro (12.9-inch) (4th generation)";
    if ([platform isEqualToString:@"iPad8,12"])     return @"iPad Pro (12.9-inch) (4th generation)";
    
    
    
    
    if ([platform isEqualToString:@"AppleTV2,1"])    return @"Apple TV 2";
    if ([platform isEqualToString:@"AppleTV3,1"])    return @"Apple TV 3";
    if ([platform isEqualToString:@"AppleTV3,2"])    return @"Apple TV 3";
    if ([platform isEqualToString:@"AppleTV5,3"])    return @"Apple TV 4";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return platform;
}

@end
